#include "led_control.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

static bool led_initialized = false;
static int gpio_pins[] = {LED1_GPIO, LED2_GPIO, LED3_GPIO, LED4_GPIO};

// 初始化LED GPIO
int led_init(void) {
    int fd;
    char gpio_str[8];
    char path[64];
    
    if (led_initialized) {
        return 0; // 已经初始化过了
    }
    
    // 导出GPIO引脚
    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (fd < 0) {
        return -1;
    }
    
    for (int i = 0; i < 4; i++) {
        snprintf(gpio_str, sizeof(gpio_str), "%d", gpio_pins[i]);
        write(fd, gpio_str, strlen(gpio_str));
    }
    fsync(fd);
    close(fd);
    
    // 设置GPIO方向为输出
    for (int i = 0; i < 4; i++) {
        snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", gpio_pins[i]);
        fd = open(path, O_WRONLY);
        if (fd >= 0) {
            write(fd, "out", 3);
            fsync(fd);
            close(fd);
        }
    }
    
    led_initialized = true;
    return 0;
}

// 设置LED状态
int led_set_state(int gpio_pin, bool state) {
    char path[64];
    int fd;
    const char *value = state ? "1" : "0";
    
    if (!led_initialized) {
        if (led_init() != 0) {
            return -1;
        }
    }
    
    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpio_pin);
    fd = open(path, O_WRONLY);
    if (fd < 0) {
        return -1;
    }
    
    write(fd, value, 1);
    fsync(fd);
    close(fd);
    
    return 0;
}

// 清理资源（可选）
void led_cleanup(void) {
    int fd;
    char gpio_str[8];
    
    if (!led_initialized) {
        return;
    }
    
    // 先关闭所有LED
    for (int i = 0; i < 4; i++) {
        led_set_state(gpio_pins[i], false);
    }
    
    // 释放GPIO（可选，通常系统关闭时会自动清理）
    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (fd >= 0) {
        for (int i = 0; i < 4; i++) {
            snprintf(gpio_str, sizeof(gpio_str), "%d", gpio_pins[i]);
            write(fd, gpio_str, strlen(gpio_str));
        }
        fsync(fd);
        close(fd);
    }
    
    led_initialized = false;
}
